package my.example.samplegridview;

import java.util.Vector;

import my.example.samplegridview.modal.product;
import my.example.samplegridview.modal.product_option;
import my.example.samplegridview.modal.product_option_value;
import o2s.utils.imageHelper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class productdescription extends Activity {
	
	public Context _context;
	public persistancestorage _ps;
	public static int activitycode = 200;
	private LayoutInflater _layoutInflater;
	AssetManager _assetManager;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.productdescription);
		_assetManager = getAssets();
		
		_layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		_context = this.getBaseContext();
		_ps = new persistancestorage(_context);
		
		final Intent i = getIntent();
		final String type = i.getStringExtra("type");
		product tmp_p = null;
		if(type.compareTo("add") == 0){
			tmp_p = new product(_context,i.getStringExtra("id"));
		}
		else if(type.compareTo("edit") == 0){
			tmp_p = currentcartitems.cartitems.elementAt(i.getIntExtra("editelementid", 0));
		}
		final product p = tmp_p;
		
		my.example.samplegridview.modal.productdescription pd = p.getProdescription();
		
		final int[] orderOptions = i.getIntArrayExtra("orderOptions");
		
		//Set Image
        ImageView iv = (ImageView)findViewById(R.id.descriptionproductimage);
        if(p.getImage().length() > 0){
			int indexer = p.getImage().lastIndexOf("/");
			String imageName = p.getImage().substring(indexer+1);
			Bitmap bitmap = imageHelper.readImageFromUrl(imageName, _context);
			//Bitmap bitmap = imageHelper.getImageFromResource(_context,p.getImage());
			iv.setImageBitmap(bitmap);
			iv.setScaleType(ImageView.ScaleType.FIT_XY);
		}
		
		TextView productname = (TextView) findViewById(R.id.descriptionproductname);
		productname.setText(pd.getName());
		
		TextView productprice = (TextView) findViewById(R.id.descriptionproductprice);
		productprice.setText("RM " + p.getPrice() );
		
		TextView productdescription = (TextView) findViewById(R.id.descriptionproductdescription);
		Spanned desc = Html.fromHtml(pd.getDescription());
		productdescription.setText(desc.toString().replaceAll("<(.|\n)*?>",""));
		
		//set options
		LinearLayout optionview = (LinearLayout) findViewById(R.id.descriptionorderoptions);
		for(int i1=0;i1<p.getProduct_options(true).size();i1++){
			LinearLayout productoption = (LinearLayout) _layoutInflater.inflate(R.layout.productoption, null);
			optionview.addView(productoption);
			TextView tv = (TextView) productoption.findViewById(R.id.productoptiontitle);
			tv.setText(" " + p.getProduct_options(true).get(i1).getProoptiondescription().getName() + " : ");
			final product_option po = p.getProduct_options(true).get(i1);
			Spinner spinner = (Spinner) productoption.findViewById(R.id.productoptionspinner);
			spinner.setAdapter(new orderOptionAdapter(_context,p.getProduct_options(true).get(i1).getProduct_option_values(true)));
			if(orderOptions != null){
				spinner.setSelection(orderOptions[i1]);
			}
			
			spinner.setOnItemSelectedListener(new OnItemSelectedListener(){

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					po.setSelectedoption(arg2);
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});
		}
		
		//ordered quantity
		EditText quantityView = (EditText) findViewById(R.id.descriptionorderquantity);
		String quantity = i.getStringExtra("orderedQuantity");
		if(quantity != null)
			quantityView.setText(quantity);
		
		final EditText remarksView = (EditText) findViewById(R.id.descriptionorderremarks);
		String remark = i.getStringExtra("orderRemarks");
		if(remark != null)
			remarksView.setText(remark);
		
		final EditText orderdetail = (EditText) findViewById(R.id.descriptionorderquantity);
		
		Button back = (Button) findViewById(R.id.descriptionback);
		back.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				Intent fromIntent = new Intent();
				setResult(activitycode,fromIntent);
				finish();
			}
			
		});
		
		Button addToCart = (Button) findViewById(R.id.descriptionaddtocart);
		addToCart.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				String orderedqty = orderdetail.getText().toString();
				if(orderedqty.trim().length() > 0){
					
					int orderedqtyint = Integer.parseInt(orderedqty);
					if(orderedqtyint > 0){
						
						p.setRemarks(remarksView.getText().toString());
						p.setOrderedQuantity(String.valueOf(orderedqtyint));
						p.setOrderBy(currentuserdetail.currentuser.getUseremail());
						p.setProductStatus("Not placed");
						
						if(type.compareTo("add") == 0){
							currentcartitems.addToCurrentCartItems(p);
						}
						else if(type.compareTo("edit") == 0){
							currentcartitems.editCurrentCartItems(i.getIntExtra("editelementid", 0), p);
						}
						
						Toast.makeText(_context, "Item added to cart.", Toast.LENGTH_SHORT).show();
						Intent fromIntent = new Intent();
						setResult(activitycode,fromIntent);
						finish();
					}
					else{
						Toast.makeText(_context, "Not a valid order quantity.", Toast.LENGTH_SHORT).show();
					}
					
				}
				else{
					Toast.makeText(_context, "You must fill in quantity.", Toast.LENGTH_SHORT).show();
				}
			}
			
		});
		
		//Add plus event
		ImageView addbutton = (ImageView)findViewById(R.id.descriptionorderquantityadd);
		addbutton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				EditText et = (EditText)findViewById(R.id.descriptionorderquantity);
				if(et.getText().toString().length() > 0){
					int tmp = Integer.parseInt(et.getText().toString());
					tmp++;
					et.setText(String.valueOf(tmp));
				}
				
			}
			
		});
		
		//Minus Button
		ImageView minusbutton = (ImageView)findViewById(R.id.descriptionorderquantityminus);
		minusbutton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				EditText et = (EditText)findViewById(R.id.descriptionorderquantity);
				if(et.getText().toString().length() > 0){
					int tmp = Integer.parseInt(et.getText().toString());
					tmp--;
					if(tmp >= 0)
						et.setText(String.valueOf(tmp));
				}
			}
			
		});
	}

	public class orderOptionAdapter extends BaseAdapter{

		Vector<product_option_value> pov;
		product_option po;
		Context context;
		orderOptionAdapter _self;
		
		public orderOptionAdapter(Context context , Vector<product_option_value> pov){
			this.context = context;
			this.pov = pov;
			_self = this;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return pov.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return pov.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int location, View arg1, ViewGroup arg2) {
			final product_option_value povi = pov.get(location);
        	
			TextView spinnerlayout = null;
			if (arg1 == null) {  // if it's not recycled, initialize some attributes
            	LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            	spinnerlayout = (TextView) li.inflate(android.R.layout.simple_spinner_item, null);
            } else {
            	spinnerlayout = (TextView) arg1;
            }
			spinnerlayout.setText(povi.getProoptionvaluedescription().getName() + " | " + povi.getPrefix() + " RM " + povi.getPrice());
			return spinnerlayout;
		}
		
	}
}
